package com.leyou.order.scheduled;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.leyou.client.item.ItemClient;
import com.leyou.order.mapper.OrderDetailMapper;
import com.leyou.order.mapper.OrderMapper;
import com.leyou.order.pojo.Order;
import com.leyou.order.pojo.OrderDetail;
import com.leyou.order.pojo.OrderStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 定时获取服务Token的任务类
 */
@Component
@Slf4j
public class OrderStatusScheduler {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ItemClient itemClient;

    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 10000L;


    /**
     * 定时清理失效订单
     * 需求：每隔1分钟清理1次
     */
    @Scheduled(fixedRate = TOKEN_REFRESH_INTERVAL)
    public void autoGetAppToken() {
        List<Order> orders = orderMapper.selectList(null);
        orders.forEach(order -> {
            //1）遍历order从中获取创建时间
            Date createTime = order.getCreateTime();
            DateTime plusMinutes = new DateTime(createTime).plusMinutes(20);
            if (plusMinutes.isBeforeNow() && order.getStatus() == OrderStatusEnum.INIT.value()) {
                //订单装填未支付以及超过20分钟后 归还库存商品 设置订单状态
                //查询订单详情
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderId(order.getOrderId());
                QueryWrapper<OrderDetail> orderDetailQueryWrapper = Wrappers.query(orderDetail);
                List<OrderDetail> orderDetails = orderDetailMapper.selectList(orderDetailQueryWrapper);
                Map<Long, Integer> resultMap = orderDetails.stream().collect(Collectors.toMap(OrderDetail::getSkuId, OrderDetail::getNum));
                //用户下单后，超过20分钟不支付，归还商品库存
                itemClient.plusStock(resultMap);
                order.setStatus(7);
                orderMapper.updateById(order);
            }
            DateTime orderTime = new DateTime(createTime).plusMinutes(120);
            //用户下单后，超过2小时未支付成功的订单，状态改为已失效。
            if (orderTime.isBeforeNow() && order.getStatus() == 7) {
                order.setStatus(OrderStatusEnum.CLOSED.value());
                orderMapper.updateById(order);
            }
        });
    }
}


